<?php

namespace common\models\base;

use common\component\BaseActiveRecord;
use Yii;
use yii\behaviors\TimestampBehavior;

/**
 * This is the model class for table "{{%base_attachment_service}}".
 *
 * @property int $id
 * @property int $service 服务
 * @property string $service_id 服务ID
 * @property string $attach_id
 * @property int $status
 * @property int $sort 排序
 * @property string $updated_at
 * @property string $created_at 创建时间
 */
class AttachmentService extends BaseActiveRecord
{

    const STATUS_DISABLE = 0;
    const STATUS_ENABLE = 1;
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{base_attachment_service}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['id', 'service', 'service_id', 'attach_id', 'status', 'sort', 'updated_at', 'created_at'], 'integer'],
            [['id'], 'unique'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'service' => 'Service',
            'service_id' => 'Service ID',
            'attach_id' => 'Attach ID',
            'status' => 'Status',
            'sort' => 'Sort',
            'updated_at' => 'Updated At',
            'created_at' => 'Created At',
        ];
    }

    public function behaviors()
    {
        return [
            [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    self::EVENT_BEFORE_INSERT => ['created_at'],
                    self::EVENT_BEFORE_UPDATE => ['updated_at']
                ]
            ]
        ];
    }

    const serviceArticleCover = 1;   //文章封面图

    const serviceAdImage = 10;  //广告图

    const serviceUserFace = 20; //用户图像
    const serviceUserMaterial = 21;  //用户申请作者的证明材料


    const serviceEmailImport = 30; //邮箱导入


    const IMAGE_CUT = 1;        //剪切
    const IMAGE_COMPRESS = 0;  //压缩

    /**
     * 生成缩略图
     * @var array
     */
    public static $thumbSize = [
        self::serviceArticleCover => [
            '278x208'=> self::IMAGE_COMPRESS,
            '140x105' => self::IMAGE_COMPRESS
        ],
        self::serviceUserFace => [
            '32x32' => self::IMAGE_COMPRESS,
            '120x120' => self::IMAGE_COMPRESS
        ]
    ];
    public function afterDelete()
    {
        parent::afterDelete();
        //删除对应的物理文件
        Attachment::removeDataAndFile($this->attach_id);
    }

    /**
     * 获取附件地址
     */
    public function getAttachment() {
        return $this->hasOne(Attachment::className(),['id'=>'attach_id']);
    }

    /**
     * 返回最大排序
     * @param $service
     * @param $service_id
     */
    public static function intMaxSort($service,$service_id) {
        $max = static::find()->where(['service'=>$service,'service_id'=>$service_id,'status'=>self::STATUS_ENABLE])->max("sort");
        return ++$max;
    }

    /**
     * 返回图片地址和ID值
     * @param $service
     * @param $service_id
     */
    public static function arrayImageAndValue($service,$service_id) {
        $data = ['url'=>'','value'=>0];
        $model = static::findOne(['service'=>$service,'service_id'=>$service_id,'status'=>self::STATUS_ENABLE]);
        if (!$model) return $data;
        $data['url'] = $model['attachment']->attachUrl();
        $data['value'] = $model->id;
        return $data;
    }

    /**
     * 更新附件
     * @param $isInsert
     * @param $service
     * @param $serviceId
     * @param $attachId
     * @return bool
     */
    public static function modifyAttachment($isInsert,$service,$serviceId,$attachId) {
        if (!$serviceId) return true;
        if ($isInsert) {
            //首次绑定时
            $model = static::findOne($attachId);
            if (!$model) {
                Yii::error("附件绑定失败,未找到附件数据");
                return false;
            }
            $model->service = $service;
            $model->service_id = $serviceId;
            $model->status = self::STATUS_ENABLE;
            if (!$model->save()){
                Yii::error("附件绑定失败，原因：".$model->getErrorsToString());
                return false;
            }
        } else {
            $models = static::find()->where(['service'=>$service,'service_id'=>$serviceId])->all();
            if ($models) {
                foreach ($models as $model) {
                    if ($model['id'] == $attachId) {
                        if ($model['status'] == self::STATUS_DISABLE) {
                            $model->updateAttributes(['status'=>self::STATUS_ENABLE]);
                        }
                    }
                    else {
                        $model->delete();
                    }
                }
            }
        }
        return true;
    }

    /**
     * 找出图片url
     * @param $size
     * @return string
     */
    public function imgSrc($size="") {
        $image = Attachment::loadRowData($this->attach_id);
        if (!$image) return "";
        //检查是否存在指定的size
        if (!isset(self::$thumbSize[$this->service][$size])) {
            return $image->attachUrl();
        }
        return $image->attachUrl($size);
    }


    public static function getImgSrcById($service_id,$size="",$service = self::serviceArticleCover) {
        $model = static::findOne(["service"=>$service,"service_id"=>$service_id,"status"=>self::STATUS_ENABLE]);
        if (!$model) {
            return "";
        }
        return $model->imgSrc($size);
    }


    public static function getImgSrcByAsID($asid,$size="") {
        $model = static::findOne($asid);
        if (!$model) {
            return "";
        }
        return $model->imgSrc($size);
    }



    public static function getFileNameById($id) {
        $model = static::findOne($id);
        if (!$model) {
            return "";
        }
        $attach = $model['attachment'];
        return $attach["path"].DIRECTORY_SEPARATOR.$attach["name"].$attach["ext"];
    }

    /**
     * 删除附件
     * @param $id
     * @return bool
     * @throws \Throwable
     * @throws \yii\db\StaleObjectException
     */
    public static function removeRecordById($id) {
        $model = static::findOne($id);
        if ($model) $model->delete();
        return true;
    }
}
